package net.tavion.angelboot.common.aop;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author : tavion
 * Date: 2016-12-02
 * Time: 16:36
 */
@Component
@Aspect
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class ScheduledAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledAspect.class);
    private static boolean scheduled = false;

    static {
        String temp = System.getProperty("app.scheduled");
        if (StringUtils.isBlank(temp)) {
            temp = System.getenv("APP_SCHEDULED");
        }
        scheduled = Boolean.parseBoolean(temp);
        LOGGER.info("Current Node Scheduled is {}", scheduled);
    }

    @Pointcut("execution(* net.tavion.angelboot..*(..)) && @annotation(org.springframework.scheduling.annotation.Scheduled)")
    public void anyScheduledServiceMethod() {
    }

    @Around("net.tavion.angelboot.common.aop.ScheduledAspect.anyScheduledServiceMethod()")
    public Object doWithServices(ProceedingJoinPoint pjp) throws Throwable {
        if (!scheduled) {
            return null;
        }
        return pjp.proceed();
    }
}
